<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" class="three-column-form">
      <el-form-item label="管理单位" prop="orgId">
        <treeselect
          v-model="queryParams.orgId"
          :options="deptOptions"
          :normalizer="normalizer"
          :show-count="true"
          placeholder="请选择管理单位"
          @select="handleDeptSelect"
        />
      </el-form-item>
      <el-form-item label="设备类别" prop="powerCate">
        <el-select v-model="queryParams.powerCate" placeholder="请选择设备类别" clearable>
          <el-option
            v-for="dict in dict.type.power_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用电场景" prop="applyScene">
        <el-select v-model="queryParams.applyScene" placeholder="请选择用电场景" clearable>
          <el-option
            v-for="dict in dict.type.apply_scene"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="用电点信息" prop="powerNo">
        <el-input
          v-model="queryParams.powerNo"
          placeholder="请输入名称或编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      
      <el-form-item label="费控类型" prop="feesChargedType">
        <el-select v-model="queryParams.feesChargedType" placeholder="请选择费控类型" clearable>
          <el-option
            v-for="dict in dict.type.fees_charged_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreatedAt"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['station:station:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['station:station:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['station:station:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['station:station:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="table-container">
      <el-table 
        v-loading="loading" 
        :data="stationList" 
        @selection-change="handleSelectionChange"
        border
        style="width: 100%">
        <el-table-column type="selection" width="55" align="center" fixed />
        <el-table-column type="index" label="序号" width="55" align="center" fixed />
        <el-table-column label="管理单位" align="center" prop="deptName" min-width="160" />   
        <el-table-column label="用电点编号" align="center" prop="powerNo" min-width="200" />
        <el-table-column label="用电点名称" align="center" prop="powerName" min-width="200" />
        <el-table-column label="用电场景" align="center" prop="applyScene" min-width="120">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.apply_scene" :value="scope.row.applyScene"/>
          </template>
        </el-table-column>
        <el-table-column label="设备类别" align="center" prop="powerCate" min-width="180">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.power_category" :value="scope.row.powerCate"/>
          </template>
        </el-table-column>
        <el-table-column label="最大通道数量" align="center" prop="maxChannels" min-width="100" />
        <el-table-column label="逻辑地址" align="center" prop="areaCode" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.areaCode }}{{ scope.row.addressCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="安装地址" align="center" prop="installAddress" min-width="200" />
        <el-table-column label="费控类型" align="center" prop="feesChargedType" min-width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.fees_charged_type" :value="scope.row.feesChargedType"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" min-width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['station:station:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['station:station:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用电点管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dialog-form">
        <el-form-item label="管理单位" prop="orgId">
          <treeselect
            v-model="form.orgId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="请选择管理单位"
            @select="handleFormDeptSelect"
          />
        </el-form-item>
        <el-form-item label="用电场景" prop="applyScene">
          <el-select v-model="form.applyScene" placeholder="请选择用电场景">
            <el-option
              v-for="dict in dict.type.apply_scene"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否开箱门" prop="isOpenDoor">
          <el-select v-model="form.isOpenDoor" placeholder="请选择是否开箱门">
            <el-option
              v-for="dict in dict.type.is_open_door"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用电点编号" prop="powerNo">
          <el-input v-model="form.powerNo" placeholder="请输入用电点编号" />
        </el-form-item>
        <el-form-item label="用电点名称" prop="powerName">
          <el-input v-model="form.powerName" placeholder="请输入用电点名称" />
        </el-form-item>
        <el-form-item label="设备类别" prop="powerCate">
          <el-select v-model="form.powerCate" placeholder="请选择设备类别">
            <el-option
              v-for="dict in dict.type.power_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="powerType">
          <el-select v-model="form.powerType" placeholder="请选择设备类型">
            <el-option
              v-for="dict in dict.type.power_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费控类型" prop="feesChargedType">
          <el-select v-model="form.feesChargedType" placeholder="请选择费控类型">
            <el-option
              v-for="dict in dict.type.fees_charged_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上行通信规约" prop="upProtocol">
          <el-select v-model="form.upProtocol" placeholder="请选择上行通信规约">
            <el-option
              v-for="dict in dict.type.up_protocol"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上行通信方式" prop="upChannel">
          <el-select v-model="form.upChannel" placeholder="请选择上行通信方式">
            <el-option
              v-for="dict in dict.type.up_channel"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下行通信方式" prop="downChannel">
          <el-select v-model="form.downChannel" placeholder="请选择下行通信方式">
            <el-option
              v-for="dict in dict.type.down_channel"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="逻辑地址" prop="areaCode" class="logic-address-item">
          <div class="logic-address-inputs">
            <el-input v-model="form.areaCode" placeholder="请输入4位区码" maxlength="4" show-word-limit />
            <el-input v-model="form.addressCode" placeholder="请输入5位地址码" maxlength="5" show-word-limit />
          </div>
        </el-form-item>
        <el-form-item label="最大通道数" prop="maxChannels">
          <el-select v-model="form.maxChannels" placeholder="请选择最大通道数">
            <el-option
              v-for="item in [1,2,4,8,12,16,20]"
              :key="item"
              :label="item.toString()"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装地址" prop="installAddress">
          <el-input v-model="form.installAddress" type="textarea" placeholder="请输入安装地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStation, getStation, delStation, addStation, updateStation } from "@/api/station/station"
import { listDept } from "@/api/system/dept"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: "Station",
  components: { Treeselect },
  dicts: ['apply_scene', 'up_channel', 'is_open_door', 'power_category', 'power_type', 'fees_charged_type', 'up_protocol', 'down_channel'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用电点管理表格数据
      stationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 更新时间时间范围
      daterangeCreatedAt: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orgId: null,
        applyScene: null,
        isOpenDoor: null,
        powerNo: null,
        powerName: null,
        powerCate: null,
        feesChargedType: null,
        upProtocol: null,
        upChannel: null,
        downChannel: null,
        createdAt: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orgId: [
          { required: true, message: "管理单位ID，关联组织机构树不能为空", trigger: "blur" }
        ],
        applyScene: [
          { required: true, message: "用电场景不能为空", trigger: "change" }
        ],
        isOpenDoor: [
          { required: true, message: "是否开箱门：1是，0否不能为空", trigger: "change" }
        ],
        powerNo: [
          { required: true, message: "用电点编号不能为空", trigger: "blur" }
        ],
        powerName: [
          { required: true, message: "用电点名称不能为空", trigger: "blur" }
        ],
        powerCate: [
          { required: true, message: "设备类别不能为空", trigger: "change" }
        ],
        powerType: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        feesChargedType: [
          { required: true, message: "费控类型不能为空", trigger: "change" }
        ],
        upProtocol: [
          { required: true, message: "上行通信规约不能为空", trigger: "change" }
        ],
        upChannel: [
          { required: true, message: "上行通信方式不能为空", trigger: "change" }
        ],
        downChannel: [
          { required: true, message: "下行通信方式不能为空", trigger: "change" }
        ],
        areaCode: [
          { required: true, message: "区码不能为空", trigger: "blur" },
          { pattern: /^\d{4}$/, message: "区码必须为4位数字", trigger: "blur" }
        ],
        addressCode: [
          { required: true, message: "地址码不能为空", trigger: "blur" },
          { pattern: /^\d{5}$/, message: "地址码必须为5位数字", trigger: "blur" }
        ],
        maxChannels: [
          { required: true, message: "最大通道数不能为空", trigger: "change" },
          { type: 'number', message: "最大通道数必须为数字", trigger: "change" }
        ],
        installAddress: [
          { required: true, message: "安装地址不能为空", trigger: "blur" }
        ],
        createdAt: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      },
      // 部门树选项
      deptOptions: [],
      // 选中的部门名称
      selectedDeptName: '',
      // 表单中选中的部门名称
      formDeptName: '',
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
  },
  methods: {
    /** 查询部门树结构 */
    getDeptTree() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId")
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    /** 部门选择事件 */
    handleDeptSelect(node) {
      this.selectedDeptName = node.label
    },
    /** 查询用电点管理列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeCreatedAt && '' != this.daterangeCreatedAt) {
        this.queryParams.params["beginCreatedAt"] = this.daterangeCreatedAt[0]
        this.queryParams.params["endCreatedAt"] = this.daterangeCreatedAt[1]
      }
      listStation(this.queryParams).then(response => {
        this.stationList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orgId: null,
        applyScene: null,
        isOpenDoor: null,
        powerNo: null,
        powerName: null,
        powerCate: null,
        powerType: null,
        feesChargedType: null,
        upProtocol: null,
        upChannel: null,
        downChannel: null,
        areaCode: null,
        addressCode: null,
        maxChannels: null,
        installAddress: null,
        createdAt: null,
        updatedAt: null
      }
      this.formDeptName = ''
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreatedAt = []
      this.selectedDeptName = ''
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加用电点管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getStation(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改用电点管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addStation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除用电点管理编号为"' + ids + '"的数据项？').then(function() {
        return delStation(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('station/station/export', {
        ...this.queryParams
      }, `station_${new Date().getTime()}.xlsx`)
    },
    /** 表单中部门选择事件 */
    handleFormDeptSelect(node) {
      this.formDeptName = node.label
    },
  }
}
</script>

<style>
/* 对话框表单样式 */
.dialog-form {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.dialog-form .el-form-item {
  width: calc(50% - 20px);
  margin: 0 10px 10px;
  box-sizing: border-box;
}

.dialog-form .el-form-item .el-form-item__content {
  width: calc(100% - 120px) !important;
}

/* 输入框和选择框样式 */
.dialog-form .el-form-item .el-input,
.dialog-form .el-form-item .el-select,
.dialog-form .el-form-item .el-date-editor {
  width: 100% !important;
}

.dialog-form .el-form-item .el-input__inner,
.dialog-form .el-form-item .el-select .el-input__inner,
.dialog-form .el-form-item .el-date-editor .el-input__inner {
  width: 100% !important;
}

/* select组件样式 */
.dialog-form .el-form-item .el-select .el-input {
  width: 100% !important;
}

/* 日期组件样式 */
.dialog-form .el-form-item .el-date-editor {
  width: 100% !important;
}

/* 搜索表单样式保持不变 */
.three-column-form .el-form-item .el-form-item__content {
  width: calc(100% - 145px) !important;
}

.three-column-form .el-form-item .el-select {
  width: 100% !important;
}

.three-column-form .el-form-item .el-select .el-input {
  width: 100% !important;
}

.three-column-form .el-form-item .el-select .el-input__inner {
  width: 100% !important;
}

.three-column-form .el-form-item .el-date-editor {
  width: 100% !important;
}

.three-column-form .el-form-item .el-date-editor .el-input__inner {
  width: 100% !important;
}

.three-column-form .el-form-item:last-child .el-form-item__content {
  width: 100% !important;
  margin-left: 0;
  text-align: right;
}

.three-column-form .el-form-item:last-child .el-button {
  margin-left: 10px;
}

/* 添加树形选择器样式 */
.three-column-form .vue-treeselect {
  width: 100%;
}

.three-column-form .vue-treeselect .vue-treeselect__control {
  border-radius: 4px;
}

/* 对话框表单中的树形选择器样式 */
.dialog-form .vue-treeselect {
  width: 100%;
}

.dialog-form .vue-treeselect .vue-treeselect__control {
  border-radius: 4px;
}

/* 逻辑地址输入框样式 */
.logic-address-item .el-form-item__content {
  width: calc(100% - 120px) !important;
}

.logic-address-inputs {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.logic-address-inputs .el-input {
  width: 48% !important;
}

.logic-address-inputs .el-input__inner {
  width: 100% !important;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  overflow-x: auto;
}

.table-container .el-table {
  min-width: 100%;
}

/* 确保表格内容不会被压缩 */
.table-container .el-table__body-wrapper {
  overflow-x: auto;
}

/* 固定列样式 */
.table-container .el-table__fixed-right {
  height: 100% !important;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
}

.table-container .el-table__fixed {
  height: 100% !important;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
}
</style>

<style scoped>
.three-column-form {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.three-column-form .el-form-item {
  width: calc(33.33% - 20px);
  margin: 0 10px 10px;
  box-sizing: border-box;
}

.three-column-form .el-form-item:last-child {
  width: 100%;
  margin: 0 10px;
  text-align: right;
}
</style>

